/**
 * Created by Dalyn on 2017/2/28.
 */
import React from "react";
import {Modal} from "antd";
import Confirm from "../../common/Confirm";
import InputBox from "../../common/InputBox";
import CascadingAddress from "./CascadingAddress";
import Select from "../../common/Select";
import Relay from "react-relay";
import CreateEnterpriseMutation from "./mutation/CreateEnterpriseMutation";
import "./css/Company.css";
import SelCompanyType from "./SelCompanyType"
import FindByPhoneMutation from "./mutation/FindByPhoneMutation"
import {hashHistory, Link} from 'react-router';
import EnterpriseTypeModal from "./children_com/EnterpriseTypeModalCreat"

/*导出组件*/
export default class CreateCompany extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            companyhint: '',
            organization: '',
            type: '',
            address: '',
            connection: '',
            account: '',
            bank: '',
            banknum: '',
            ratepayer: '',
            remark: '',
            name: '',
            password: '',
            userId: '',
            userName: "",

            mainService: "",
            enType_oneActive: "",

        };

        this.Style = {};
        this.oArr1 = [
            {text: "国内", value: "0"}
        ]

        this.sheng = '';
        this.shi = '';
        this.xian = '';
        this.i = 0;
        this.j = 0;

        this.updataChecked = this.updataChecked.bind(this);
    }

    componentWillMount() {

        this.Style1 = {
            main: {
                width: '100%',
                height: '100%'
            },
            p_title: {
                width: "100%",
                height: 57,
                borderBottom: "1px #ededed solid"
            },
            div_context: {
                backgroundColor: '#a0d468',
                marginRight: 20,
                marginTop: 20,
                marginBottom: 20
            },

            sp_database: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #60caf1",
            },
            sp_financeinfo: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #68cbca",
            },
            sp_admin: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #fb6e64",
            },
            sp_other: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #e9ba65",
            },

            inputbox_line: {
                paddingRight: 745,
                marginTop: 20,
                width: 315,
                height: 32
            },
            inputbox_linetop: {
                paddingRight: 745,
                marginTop: 70,
                width: 315,
                height: 32
            },
            inputbox_linemulit: {
                paddingRight: 190,
                marginTop: 20,
                width: 882,
                height: 167,
                alignItems: 'flex-start',
                textmarginTop: 0

            },
            p_companytype: {
                marginTop: 20,
                width: 315,
                height: 32,
                lineHeight: "32px",
                marginLeft: "132px",
                paddingLeft: 10,
                background:"#f5fbf0"
            }

        }

        this.Style = {
            main: {
                width: '100%',
                height: '100%'
            },
            p_title: {
                height: 57,
                borderBottom: "1px #ededed solid"
            },
            div_context: {
                backgroundColor: '#fff',
                marginRight: 20,
                marginTop: 10,
                marginBottom: 20
            },

            sp_database: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #a0d468",
            },
            sp_financeinfo: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #68cbca",
            },
            sp_admin: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #fb6e64",
            },
            sp_other: {
                lineHeight: "15px",
                display: "block",
                color: '#333',
                fontSize: 15,
                width: 109,
                height: 15,
                padding: "20px 0",
                textAlign: "center",
                borderBottom: "3px solid #e9ba65",
            },

            //asdasd
            inputbox_line: {
                paddingRight: 755,
                paddingLeft:10,
                marginTop:20,
                marginLeft: 10,
                width: 315,
                height: 32,
                borderColor:"transparent",
                borderStyle:"solid",
                background:"#f5fbf0"
            },
            inputbox_linetop: {
                paddingRight: 745,
                marginTop: 70,
                width: 315,
                height: 32,
                borderColor:"transparent",
                borderStyle:"solid",
                background:"#f5fbf0"
            },
            inputbox_linemulit: {
                paddingRight: 190,
                marginTop: 20,
                width: 882,
                height: 167,
                alignItems: 'flex-start',
                textmarginTop: 0,
                borderColor:"#a0d468",
                paddingLeft:5,
                paddingTop:5
            },

        }


    }
    checkUser() {
        this.refs._user_name.setState({
            text: "",
        })

        let telephone1 = this.refs._user_phone.state.text;
        let re_telephone = /^(((13[0-9]{1})|(17[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
        let re_telephone1 = /^400[0-9]{7}/;
        let re_telephone2 = /^800[0-9]{7}/;
        let re_telephone3 = /^0[0-9]{2,3}[0-9]{8}/;
        let re_telephone4 = /^0[0-9]{2,3}-[0-9]{8}/;
        let telephone;
        if (re_telephone.test(telephone1) || re_telephone1.test(telephone1) || re_telephone2.test(telephone1) || re_telephone3.test(telephone1) || re_telephone4.test(telephone1)) {
            telephone = telephone1;
            this.setState({
                userName: ""
            });
        } else if (telephone1 == "") {
            this.setState({
                userName: ""
            });
        } else {
            this.setState({
                userName: "联系方式格式错误，请重新输入"
            });
        }
        Relay.Store.commitUpdate(
            new FindByPhoneMutation({
                phone: this.refs._user_phone.state.text,
            }),
            {
                onFailure: () => {
                    alert('请求失败');
                },
                onSuccess: (response) => {
                    let errorCode = response.findByPhone.findByPhone.errorCode;
                    if (errorCode == '000001') {
                        this.refs._user_name.setState({
                            disabled: false
                        })

                        this.refs._user_password.setState({
                            text: "123456",
                            disabled: true
                        })
                    } else {
                        let user = response.findByPhone.findByPhone.userModel;

                        this.setState({
                            userId: user.uid,
                        })

                        this.refs._user_name.setState({
                            text: user.name,
                            disabled: true
                        })

                        this.refs._user_password.setState({
                            disable: true,
                            text: "******"
                        })

                    }


                }
            }
        )

    }

    /**错误提示框*/
    showError(title, value) {

        Modal.error({
            title: !title ? "提示：" : title,
            content: value,
            width: 390
        });
    }


    showInfo(title, value) {
        Modal.info({
            title: !title ? "提示：" : title,
            content: value,
            width: 390
        });
    }

    // 点击企业类型设置时更新mainService状态.
    updataChecked(checked, active) {
        this.setState({
            mainService: checked,
            enType_oneActive: active
        })
    }


    save() {
        // console.log(this.refs.selecttab.state.provSelectedValue);
        // console.log(this.refs.selecttab.addr_arr);
        // for(let i = 0; i<this.refs.selecttab.addr_arr[0].length;  i++){
        //
        // }
        // console.log(this.refs.selecttab.addr_arr[73][11][1]);
        //  console.log(this.companyname.value)
        //  console.log(this.enterpriseCode.value)


        // let test2 = this.refs._enterpriseCode.state.text;
        // let reg = /^([0-9A-Z]){8}[-][0-9]$/;
        // if (reg.test(test2) == false) {
        //     return;
        // }
        if (this.state.userName.length > 0 || this.state.companyhint.length > 0 || this.state.organization.length > 0 || this.state.connection.length > 0 || this.state.account.length > 0 || this.state.bank.length > 0 || this.state.banknum.length > 0 || this.state.ratepayer.length > 0 || this.state.organization.length > 0) {
            this.showError("error", "参数错误,请仔细检查！");
            return;
        }

        let enterType;
        if (this.state.enType_oneActive === "") {
            enterType = ''
        } else {
            enterType = this.refs._enterpriseType.state.OneList[this.state.enType_oneActive].dicId;
        }


        let mainService = this.state.mainService,
            serviceType = enterType;


        if (this.refs._enterpriseName.state.text != "" && this.refs._enterpriseCode.state.text != "" && this.refs._user_phone.state.text != '') {
            let serviceType
            if (this.refs._enterpriseType.state.OneList.length > 0) {
                serviceType = this.refs._enterpriseType.state.OneList[this.refs._enterpriseType.state.enType_oneActive].dicId;
            } else {
                serviceType = '';
            }

            let mainService = this.refs._enterpriseType.state.SubData;
            let userPhone = this.refs._user_phone.state.text;
            let userName = this.refs._user_name.state.text;
            let province = this.sheng;
            let city = this.shi
            let region = this.xian
            let telephone = this.refs._telephone.state.text
            let bankAccount = this.refs._bankAccount.state.text;
            let bankName = this.refs._bankName.state.text;
            let taxpayerNo = this.refs._taxpayerNo.state.text;
            let bankNo = this.refs._bankNo.state.text;
            let remark = this.refs._remark.state.text;
            let userId = this.state.userId;
            let enterpriseName = this.companyname;
            let enterpriseCode = this.enterpriseCode;
            let entype = this.entype;
            let address1 = this.refs._address.state.text;

            Relay.Store.commitUpdate(
                new CreateEnterpriseMutation({
                    userId: userId,
                    enterpriseName: enterpriseName,
                    enterpriseCode: enterpriseCode,
                    entype: entype,
                    countryType: 1,
                    province: province,
                    city: city,
                    region: region,
                    address: address1,
                    telephone: telephone,
                    bankAccount: bankAccount,
                    bankName: bankName,
                    taxpayerNo: taxpayerNo,
                    bankNo: bankNo,
                    remark: remark,
                    userName: userName,
                    userPhone: userPhone,
                    mainService: mainService,
                    serviceType: enterType

                }),
                {
                    onFailure: () => {
                        alert('请求失败');
                    },
                    onSuccess: (response) => {
                        if (response.createEnterprise.data.errorCode == 0 || response.createEnterprise.data.errorCode == "000005") {
                            this.showInfo("", "创建企业成功");
                            hashHistory.push("/companymanage");
                        } else {
                            this.showError("error", response.createEnterprise.data.value);
                        }
                    }
                }
            )
        } else {
            this.showError("错误", "企业名称、组织机构代码和企业管理员手机都不能为空！");
        }

    }

//////yui
    bluron(type) {
        switch (type) {

            case 'companyhint':
                let companyname1 = this.refs._enterpriseName.state.text;
                let reg_com = /^[a-zA-Z\u4e00-\u9fa5（）]{4,40}$/;
                this.companyname = companyname1;
                if (!reg_com.test(companyname1)) {
                    this.setState({
                        companyhint: "企业名称格式错误，请重新输入(只能包含汉字、字母和中文状态下的（）,长度4-40)"
                    });
                    return;
                }
                if (this.companyname == "") {
                    this.setState({
                        companyhint: "企业名称不能为空"
                    });
                } else {
                    this.setState({
                        companyhint: ""
                    });
                }
                return;

            case 'organization':
                let enterpriseCode1 = this.refs._enterpriseCode.state.text;
                let re_enterpriseCode = /^([0-9A-Z]){8}[-][0-9A-Z]$/;

                if (re_enterpriseCode.test(enterpriseCode1)) {
                    this.enterpriseCode = enterpriseCode1;

                    this.setState({
                        organization: ""
                    });
                } else if (enterpriseCode1 == "") {
                    this.setState({
                        organization: "组织结构代码不能为空"
                    });
                } else {
                    this.setState({
                        organization: "组织结构代码格式错误，请重新输入"
                    });
                }
                return;
            case 'connection':
                let telephone1 = this.refs._telephone.state.text;
                let re_telephone = /^[+]{0,1}(\d){1,3}([-]?((\d)){1,12})+$/;
                let telephone;
                if (re_telephone.test(telephone1)) {
                    telephone = telephone1;
                    this.setState({
                        connection: ""
                    });
                } else if (telephone1 == "") {
                    this.setState({
                        connection: ""
                    });
                } else {
                    this.setState({
                        connection: "联系方式格式错误，请重新输入"
                    });
                }
                return;

            case 'account':
                let bankAccount1 = this.refs._bankAccount.state.text;

                let re_bankAccount = /^[a-zA-Z\u4e00-\u9fa5（）]{2,200}$/;
                let bankAccount;

                if (re_bankAccount.test(bankAccount1)) {
                    bankAccount = bankAccount1;
                    this.setState({
                        account: ""
                    });
                } else if (bankAccount1 == "") {
                    this.setState({
                        account: ""
                    });
                } else {
                    this.setState({
                        account: "开户名称格式错误，请重新输入"
                    });
                }
                return;

            case 'bank':
                let bankName1 = this.refs._bankName.state.text;
                let re_bankName = /^[a-zA-Z\u4e00-\u9fa5]{2,200}$/;
                let bankName;
                if (re_bankName.test(bankName1)) {
                    bankName = bankName1;
                    this.setState({
                        bank: ""
                    });
                } else if (bankName1 == "") {
                    this.setState({
                        bank: ""
                    });
                } else {
                    this.setState({
                        bank: "开户银行格式错误，请重新输入"
                    });
                }
                return;

            case 'banknum':
                let bankNo1 = this.refs._bankNo.state.text;
                let re_bankNo = /^\d{0,30}$/;
                let bankNo;
                if (re_bankNo.test(bankNo1)) {
                    bankNo = bankNo1;
                    this.setState({
                        banknum: ""
                    });
                } else if (bankNo1 == "") {
                    this.setState({
                        banknum: ""
                    });
                } else {
                    this.setState({
                        banknum: "银行账号格式错误，请重新输入"
                    });
                }
                return;

            case 'ratepayer':
                let taxpayerNo1 = this.refs._taxpayerNo.state.text;
                let re_taxpayerNo = /^[0-9]{9,20}$/;
                let taxpayerNo;
                if (re_taxpayerNo.test(taxpayerNo1)) {
                    taxpayerNo = taxpayerNo1;
                    this.setState({
                        ratepayer: ""
                    });
                } else if (taxpayerNo1 == "") {
                    this.setState({
                        ratepayer: ""
                    });
                } else {
                    this.setState({
                        ratepayer: "纳税人识别号格式错误，请重新输入"
                    });
                }
                return;

        }
    }

    showType() {
        this.refs.selCompanyType.setState({
            visible: "true",
        })

    }

    getMessage(space, id) {
        switch (space) {
            case 'prov':
                this.shi = '';
                this.xian = '';
                //console.warn(space+'-----'+id)
                this.sheng = id;
                return;
            case 'city':
                this.xian = '';
                //console.warn(space+'-----'+id)
                this.shi = id;
                return;
            case 'district':
                //console.warn(space+'-----'+id)
                this.xian = id;
                return;
        }
    }

    ///asdasdasdasdasdasdasd

    render() {
        return (
            <div style={this.Style.main}>
                <div style={this.Style.div_context}>
                    <div style={{
                        position: "relative",
                        width: "100%",
                        height: 480,
                        backgroundColor: "#fff",
                        marginBottom: "10px"
                    }}>
                        <p style={this.Style.p_title}>
                            <span className="company_hea-tit">基础资料</span>
                        </p>
                        <div className="company_form--divItem">
                            <InputBox titletext={'企业名称'} className="company_form--divItem re_font--MicYaHei" style={this.Style.inputbox_line} space={15} ref={'_enterpriseName'}
                                      minlength={4} maxlength={40} bluron={this.bluron.bind(this, 'companyhint')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "86px"
                        }}>{this.state.companyhint}</span>
                        <span className="star1" style={{
                            display: "block",
                            position: "absolute",
                            left: "45px",
                            top: "85px",
                            width: "11px",
                            height: "18px"
                        }}></span>

                        <span className="star2" style={{
                            display: "block",
                            position: "absolute",
                            left: "15px",
                            top: "140px",
                            width: "11px",
                            height: "18px"
                        }}></span>
                        <div className="company_form--divItem">
                            <InputBox titletext={'组织结构代码'} className="company_form--divItem re_font--MicYaHei" style={this.Style.inputbox_line} space={20}
                                      ref={'_enterpriseCode'} maxlength={50}
                                      bluron={this.bluron.bind(this, 'organization')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "138px"
                        }}>{this.state.organization}</span>

                        <EnterpriseTypeModal Sty={this.Style1} updaChecked={this.updataChecked} ref={'_enterpriseType'}
                        />

                        <span style={{marginLeft: "63px",fontSize:14}} className="re_font--MicYaHei">企业地址</span>
                        <div className="company_select" style={{display:"inline-block"}}>
                            <Select className="enter_type--arr_select" oArr={this.oArr1} style={{
                                marginLeft: "13px",
                                marginTop: "20px",
                                width: 98,
                                height: 30,
                                display: "block"
                            }}  />
                        </div>
                        <div className="company_select--item" style={{marginBottom: 20, marginLeft: "180px"}}>
                            <CascadingAddress ref={'selecttab'} getMessage={this.getMessage.bind(this)}/>
                        </div>
                        <div className="company_form--divItem">
                            <InputBox titletext={'详细地址'} style={this.Style.inputbox_linetop} space={20} ref={'_address'}
                                      maxlength={50} bluron={this.bluron.bind(this, 'address')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "347px"
                        }}>{this.state.address}</span>
                        <div className="company_form--divItem">
                            <InputBox titletext={'联系方式'} style={this.Style.inputbox_line} space={20} ref={'_telephone'}
                                      maxlength={13} bluron={this.bluron.bind(this, 'connection')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "401px"
                        }}>{this.state.connection}</span>
                    </div>

                    <div style={{
                        width: "100%",
                        height: 300,
                        backgroundColor: "#fff",
                        marginBottom: "10px",
                        position: "relative"
                    }}>
                        <p style={this.Style.p_title}>
                            <span className="company_hea-tit">财务信息</span>
                        </p>
                        <div className="company_form--divItem">
                            <InputBox titletext={'开户名称'} style={this.Style.inputbox_line} space={20} ref={'_bankAccount'}
                                      maxlength={50} bluron={this.bluron.bind(this, 'account')}/>
                        </div>
                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "86px"
                        }}>{this.state.account}</span>
                        <div className="company_form--divItem">
                            <InputBox titletext={'开户银行'} style={this.Style.inputbox_line} space={20} ref={'_bankName'}
                                      maxlength={50} bluron={this.bluron.bind(this, 'bank')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "138px"
                        }}>{this.state.bank}</span>
                        <div className="company_form--divItem">
                        <InputBox titletext={'银行账号'} style={this.Style.inputbox_line} space={20} ref={'_bankNo'}
                                  maxlength={19} minlength={16} bluron={this.bluron.bind(this, 'banknum')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "192px"
                        }}>{this.state.banknum}</span>
                        <div className="company_form--divItem">
                            <InputBox titletext={'纳税人识别号'} style={this.Style.inputbox_line} space={20} ref={'_taxpayerNo'}
                                      maxlength={20} minlength={15} bluron={this.bluron.bind(this, 'ratepayer')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "246px"
                        }}>{this.state.ratepayer}</span>
                    </div>

                    <div style={{
                        position: "relative",
                        width: "100%",
                        height: 250,
                        backgroundColor: "#fff",
                        marginBottom: "10px"
                    }}>
                        <p style={this.Style.p_title}>
                            <span className="company_hea-tit">企业管理员</span>
                        </p>

                        <span className="star1" style={{
                            display: "block",
                            position: "absolute",
                            left: "70px",
                            top: "85px",
                            width: "11px",
                            height: "18px"
                        }}></span>
                        <div className="company_form--divItem">
                            <InputBox titletext={'手机'} style={this.Style.inputbox_line} space={20} disabled={false}
                                      maxlength={11}
                                      defaultvalute={''} bluron={this.checkUser.bind(this)} ref={'_user_phone'}/>
                        </div>


                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "90px"
                        }}>{this.state.userName}</span>
                        <div className="company_form--divItem">
                            <InputBox titletext={'姓名'} style={this.Style.inputbox_line} space={20}
                                      defaultvalute={''} ref={'_user_name'}/>
                            <InputBox titletext={'密码'} style={this.Style.inputbox_line} space={20}
                                      defaultvalute={''} ref={'_user_password'}/>
                        </div>

                    </div>

                    <div style={{
                        width: "100%",
                        height: 323,
                        backgroundColor: "#fff",
                        marginBottom: "10px"
                    }}>
                        <p style={this.Style.p_title}>
                            <span className="company_hea-tit">其他</span>
                        </p>

                        <div className="company_form--divItem">
                            <InputBox titletext={'备注'} style={this.Style.inputbox_linemulit} space={20} multiline={true}
                                      ref={'_remark'} maxlength={200} bluron={this.bluron.bind(this, 'remark')}/>
                        </div>

                        <span style={{
                            color: "#ff6f64",
                            position: "absolute",
                            left: "480px",
                            top: "86px"
                        }}>{this.state.remark}</span>
                        <Confirm className="re_font--MicYaHei" tcontext="创建企业" style={{
                            width: 96,
                            height: 35,
                            linHeight:35,
                            display: "block",
                            color: "#fff",
                            fontSize: 14,
                            marginLeft: 140,
                            marginTop: 30,
                            fontFamily:"Microsoft YaHei",
                            backgroundColor: "#a0d468",
                            borderRadius:5
                        }} touch={this.save.bind(this)}/>
                    </div>

                </div>

                <SelCompanyType ref={'selCompanyType'}> </SelCompanyType>
            </div>

        )
    }
}